package cn.thoughtworks.school.programCenter.services;

import cn.thoughtworks.school.programCenter.entities.ReviewQuiz;
import cn.thoughtworks.school.programCenter.repositories.ReviewQuizRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class ReviewQuizService {
    @Autowired
    private ReviewQuizRepository reviewQuizRepository;

    public void saveReviewQuiz(Map map) {
        ReviewQuiz wrapReviewQuiz = wrapReviewQuiz(map);
        ReviewQuiz existReviewQuiz = reviewQuizRepository.findByAssignmentIdAndQuizIdAndStudentId(wrapReviewQuiz.getAssignmentId(), wrapReviewQuiz.getQuizId(), wrapReviewQuiz.getStudentId());

        if (Objects.isNull(existReviewQuiz)) {
            reviewQuizRepository.save(wrapReviewQuiz);
        }

    }

    private ReviewQuiz wrapReviewQuiz(Map map) {
        Long studentId = Long.parseLong(map.get("studentId").toString());
        Long taskId = Long.parseLong(map.get("taskId").toString());
        Long assignmentId = Long.parseLong(map.get("assignmentId").toString());
        Long quizId = Long.parseLong(map.get("quizId").toString());
        return new ReviewQuiz(studentId, taskId, quizId, assignmentId, "已提交", new Date());
    }

    public boolean isSubmitted(Long assignmentId, Long studentId) {
        List<ReviewQuiz> reviewQuizs = reviewQuizRepository.findByAssignmentIdAndStudentId(assignmentId, studentId);
        return reviewQuizs.size() > 0;
    }

    public List<ReviewQuiz> findByTaskIdAndAssignmentId(Long taskId, Long assignmentId) {
        return reviewQuizRepository.findByTaskIdAndAssignmentId(taskId, assignmentId);
    }
}
